/**
 * TagSpaces - universal file and folder organizer
 * Copyright (C) 2017-present TagSpaces UG (haftungsbeschraenkt)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License (version 3) as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 */

import React, { ChangeEvent, useRef, useReducer, useEffect } from 'react';
import { styled } from '@mui/material/styles';
import { useDispatch } from 'react-redux';
import Button from '@mui/material/Button';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogTitle from '@mui/material/DialogTitle';
import Dialog from '@mui/material/Dialog';
import DialogCloseButton from '-/components/dialogs/DialogCloseButton';
import { useTheme } from '@mui/material/styles';
import useMediaQuery from '@mui/material/useMediaQuery';
import { QRCode } from 'react-qrcode-logo';
import InfoIcon from '-/components/InfoIcon';
import InputAdornment from '@mui/material/InputAdornment';
import TextField from '@mui/material/TextField';
import MenuItem from '@mui/material/MenuItem';
import PlatformIO from '-/services/platform-facade';
import Links from 'assets/links';
import { extractTitle } from '@tagspaces/tagspaces-common/paths';
import { useTranslation } from 'react-i18next';
import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';
import { useNotificationContext } from '-/hooks/useNotificationContext';
import { generateClipboardLink } from '-/utils/dom';

const PREFIX = 'LinkGeneratorDialog';

const classes = {
  root: `${PREFIX}-root`,
};

const StyledDialog = styled(Dialog)(({ theme: Theme }) => ({
  [`& .${classes.root}`]: {
    marginTop: 12,
    '& .MuiInputBase-root': {
      height: 450,
    },
  },
}));

interface Props {
  open: boolean;
  onClose: () => void;
  path: string;
  locationId?: string;
}

const QRTextField = TextField;

function LinkGeneratorDialog(props: Props) {
  const { open, onClose, path } = props;
  const { t } = useTranslation();
  const { showNotification } = useNotificationContext();
  const { switchLocationTypeByID, switchCurrentLocationType } =
    useCurrentLocationContext();
  const linkValidityDuration = useRef<number>(60 * 15);
  const signedLink = useRef<string>(undefined);
  const [ignored, forceUpdate] = useReducer((x) => x + 1, 0);
  const theme = useTheme();
  const fullScreen = useMediaQuery(theme.breakpoints.down('md'));

  useEffect(() => {
    setSignedLink();
  }, []);

  function setSignedLink() {
    //if (switchLocationType) {
    switchLocationTypeByID(props.locationId).then((currentLocationId) => {
      signedLink.current = PlatformIO.getURLforPath(
        path,
        linkValidityDuration.current,
      );
      forceUpdate();
      return switchCurrentLocationType();
    });
  }

  return (
    <StyledDialog
      open={open}
      onClose={onClose}
      fullScreen={fullScreen}
      keepMounted
      scroll="paper"
    >
      <DialogTitle>
        {t('core:generateDownloadLink')}{' '}
        <DialogCloseButton testId="closeLinkGeneratorTID" onClose={onClose} />
      </DialogTitle>
      <DialogContent style={{ overflow: 'auto' }}>
        <TextField
          style={{ marginTop: 8 }}
          select
          fullWidth={true}
          label={
            <>
              {t('core:linkValidity')}
              <InfoIcon tooltip={t('core:linkValidityTooltip')} />
            </>
          }
          value={linkValidityDuration.current}
          onChange={(event: ChangeEvent<HTMLInputElement>) => {
            linkValidityDuration.current = parseInt(event.target.value, 10);
            setSignedLink();
          }}
        >
          <MenuItem value={60 * 15}>15 {t('core:minutes')}</MenuItem>
          <MenuItem value={60 * 60}>60 {t('core:minutes')}</MenuItem>
          <MenuItem value={60 * 60 * 24}>1 {t('core:day')}</MenuItem>
          <MenuItem value={60 * 60 * 24 * 3}>3 {t('core:days')}</MenuItem>
          <MenuItem value={60 * 60 * 24 * 7}>7 {t('core:days')}</MenuItem>
        </TextField>
        <TextField
          margin="dense"
          name="path"
          style={{ marginTop: 15 }}
          InputProps={{
            readOnly: true,
            endAdornment: (
              <InputAdornment position="start">
                <Button
                  data-tid="copySharingLinkTID"
                  onClick={() => {
                    const entryTitle = extractTitle(
                      path,
                      true,
                      PlatformIO.getDirSeparator(),
                    );
                    const clibboardItem = generateClipboardLink(
                      signedLink.current,
                      entryTitle,
                    );
                    navigator.clipboard.write(clibboardItem).then(() => {
                      showNotification(t('core:linkCopied'));
                    });
                  }}
                  color="primary"
                >
                  {t('core:copy')}
                </Button>
              </InputAdornment>
            ),
          }}
          label={
            <>
              {t('core:downloadLink')}
              {/* <InfoIcon
                tooltip={t(
                  'Link for time limited sharing on the Internet'
                )}
              /> */}
            </>
          }
          fullWidth={true}
          value={signedLink.current}
        />
        <QRTextField
          margin="dense"
          name="path"
          label={t('core:qrCode')}
          value={' '}
          InputProps={{
            readOnly: true,
            startAdornment: (
              <InputAdornment position="start">
                <QRCode
                  id="qr-code-link"
                  value={signedLink.current}
                  size={350}
                  enableCORS={true}
                  // logoWidth={64}
                  // logoHeight={64}
                  // logoImage=""
                />
              </InputAdornment>
            ),
          }}
          classes={{
            root: classes.root,
          }}
        />
      </DialogContent>
      <DialogActions
        style={{
          justifyContent: 'space-between',
          padding: fullScreen ? '10px 30px 30px 30px' : undefined,
        }}
      >
        <Button
          variant="text"
          data-tid="helpSearchButtonTID"
          onClick={() => {
            PlatformIO.openUrl(Links.documentationLinks.sharing);
          }}
        >
          {t('help')}
        </Button>
        <Button
          data-tid="closeLinkTID"
          onClick={onClose}
          variant="contained"
          color="primary"
        >
          {t('core:close')}
        </Button>
      </DialogActions>
    </StyledDialog>
  );
}

export default LinkGeneratorDialog;
